package cn.itcast.n4_共享模型_管程;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import static cn.itcast.util.Sleeper.sleep;

/**
 * <p>
 * Test40_ReentrantLock_可重入性
 * </p>
 *
 * @author flyduck
 * @since 2024-10-11
 */
@Slf4j(topic = "c.Test42_ReentrantLock_锁超时")
public class Test42_ReentrantLock_锁超时 {

    private static ReentrantLock reentrantLock = new ReentrantLock();

    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            log.debug("尝试获取锁");
            try {
                if (reentrantLock.tryLock(2, TimeUnit.SECONDS)) {
                    try {
                        log.debug("获取到锁了");
                    }finally {
                        reentrantLock.unlock();
                    }
                }else {
                    log.debug("没有获取到锁");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }, "t1");

        reentrantLock.lock();
        try {
            log.debug("获取到锁了");
            t1.start();
            sleep(1);
        }finally {
            log.debug("释放了锁");
            reentrantLock.unlock();
        }



    }
}
